# -*- coding: utf-8 -*-
__author__ = 'Paul'
from five import grok
from zope.interface import Interface
from Products.CMFCore.utils import getToolByName
from Acquisition import aq_inner
from zope.site.hooks import getSite
from OFS.interfaces import IOrderedContainer
from time import localtime
from DateTime import DateTime
from datetime import date
import datetime
import calendar
from Products.ATContentTypes.interface.document import IATDocument as IDoc

from Products.ATContentTypes.interface import IATFolder
from Products.bpContents.articulo import IArticulo
from Products.bpContents.directorio import IDirectorio
from zope.component import queryMultiAdapter,getMultiAdapter
from zope.viewlet.interfaces import IViewletManager,IViewlet
from zope.interface import alsoProvides
from Products.Five.browser import BrowserView as View
from zope.publisher.interfaces.browser import IBrowserRequest
from plone.app import customerize
from zope.traversing.interfaces import ITraverser, ITraversable
from Products.bpContents.utils import Utilidades
from zope.formlib import form
from plone.app.users.browser.register import RegistrationForm
from zope.interface import implements
from quintagroup.formlib.captcha import Captcha
from quintagroup.formlib.captcha import CaptchaWidget
from Acquisition import aq_acquire, aq_inner, aq_base, aq_chain

##from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile


class DirectorioView(grok.View):
    """Pagina principal del canal"""
    grok.context(Interface)
    grok.name('directorio_view')

    def getCanal(self):
        """devuelve el canal en el que me encuntro
        """
        context=aq_inner(self.context)
        canal=self.request.form["canal"]
        self.canal = canal
        home = getSite()
        portal_url  = getToolByName(context, "portal_url")
        areaFolder=None
        portal = portal_url.getPortalObject()

        try:
            folderCanal=aq_inner(portal["home"][canal])
            folder_path = '/'.join(folderCanal.getPhysicalPath())
            if hasattr(folderCanal,"depatamento"):
                areaFolder=folderCanal["departamento"]
            elif hasattr(folderCanal,"areas"):
                areaFolder=folderCanal["areas"]
        except :
            print "DirectorioView: no se encontro el canal"
        resObj=[]
        tmpOrder=[]

        for paquete in self.getContenido(folderCanal):

            if paquete["tipo"]=="Folder":
                    if paquete["id"] not in ('servicio-de-prestamos','multicarpeta'):
                        retcupObj= aq_inner(self.context.unrestrictedTraverse(paquete["path"]))
                        paquete["content"]=self.getContenido(retcupObj)
                    else:
                        paquete["content"]=[]
                    #paquete["content"]=[]

            tmpOrder.append(paquete)
        return sorted(tmpOrder)





    def getContenido(self,raizO):
        """Dada una Folder, devuelve el contenido de una carpeta"""
        flag=0
        resObj=[]

        for elem in raizO.getFolderContents():
            if elem.id!=raizO.id:
                paquete=self.empaqueta(elem)
                if paquete["visible"] and paquete["id"] not in ('departamentos','departamentos-1','areas'):
                    paquete['position']=flag
                    resObj.append(paquete)
                    flag=flag+1

        return sorted(resObj)




    def empaqueta(self,objAempaquetar):
        """convierte los valores de un objeto en otro taburado"""

        objetoPosta=self.context.unrestrictedTraverse(objAempaquetar.getPath())
        canal=dict()
        canal["id"]=objAempaquetar.id
        canal["tipo"]=objAempaquetar.portal_type
        canal['titulo']=objAempaquetar.Title
        canal['url']  =  objAempaquetar.getURL()
        canal['path']=objAempaquetar.getPath()
        canal["visible"]=True
        try:
            canal["visible"]=not objetoPosta.getExcludeFromNav()
        except:
            print "DirectorioView: el objeto no tiene el parametro de excluir de la navegacion"
        return canal


    def getAreas(self):
        """Devuelve departamenteos de la BP"""
        from Products.bpContents.departamento import IDepartamento
        catalogo = getToolByName(self.context, 'portal_catalog')
        folderCanal=None
        areaFolder=None
        home= getSite()
        if hasattr(home["home"],"conocenos"):
            folderCanal=home["home"]["conocenos"]
        if folderCanal:
            if hasattr(folderCanal,"depatamentos"):
                areaFolder=folderCanal["departamentos"]
            elif hasattr(folderCanal,"areas"):
                areaFolder=folderCanal["areas"]

            deptos=catalogo(object_provides=IDepartamento.__identifier__)
        else:
            return None
        return deptos

    def getEnlaces(self):
        """Devuelve los enlaces externos, CATALOGO BLOG etc."""
        catalog = getToolByName(self.context, 'portal_catalog')
        home=getSite()

        try:
            folderEnlaces=home["home"]["contenidos-externos"]
        except :
            print "DirectorioView: no existe la carpeta"
            return None

        path = "/".join(folderEnlaces.getPhysicalPath())
        result = catalog(portal_type="Link",path={"query": path, "depth": 1})
        ramas=[]
        pp=0
        for elem in result:
            elemOb=aq_inner(self.context).unrestrictedTraverse(elem.getPath())

            orderDic={}
            orderDic["pos"]     = pp
            ##self.get_position_in_parent(elemOb)
            orderDic["brain"]   =   {"titulo":elem.Title,"remoto":elemOb.getRemoteUrl(),"descri":elemOb.Description}
            pp=pp+1
            ramas.append(orderDic)


        if len(ramas)>0:
            return sorted(ramas)
        else:
            return None

    def dameCarpetas(self,ruta,catalog):
        """ Devuelve las carpetas del nivel 0
        """
        result=[]
        raizID=ruta[ruta.rfind("/")+1:]
        carpetas = catalog({'object_provides': (IDoc.__identifier__,IArticulo.__identifier__,IATFolder.__identifier__),
                            'path':{'query': ruta, 'depth': 1},},
        )
        flag=0
        for elem in carpetas:
            elemObj=self.context.unrestrictedTraverse(elem.getPath())
            if elem.id!=raizID:
                if elem.portal_type in ("ATFolder","Folder"):
                    if not elemObj.getExcludeFromNav():
                        result.append(elem)
                else:
                    result.append(elem)

        return result

    def dameContenidos(self,rutaCarpeta,catalog):
        """ Devuelve todo lo que se encuetra en una carpeta
        """
        items = catalog(path={'query': rutaCarpeta, 'depth': 1},poral_type=("Document",))
        return items

    def getIMG(self,ruta,catalog):
        search=catalog(
            path=ruta,
            object_provides="Products.ATContentTypes.interfaces.image.IATImage",
            sort_on='modified',
            sort_order='reverse')

        if len(search)>0:
            elemOb=self.context.unrestrictedTraverse(search[0].getPath())
            return elemOb
        else:
            return None

    def get_position_in_parent(self,obj):
        """ Use IOrderedContainer interface to extract the object's manual ordering position
        """
        parent = aq_inner(obj.aq_parent)
        ordered = IOrderedContainer(parent, None)
        if ordered is not None:
            return ordered.getObjectPosition(obj.getId())
        return 0

    def sort_by_position(self,a, b):
        """
        Python list sorter cmp() using position in parent.

        Descending order.
        """
        return self.get_position_in_parent(a) - self.get_position_in_parent(b)

class CategoriaLista(grok.View):
    grok.context(Interface)
    grok.name('categoriaList_view')

    def update(self):
        # Hide the editable-object border
        self.request.set('disable_border', True)
        if 'rama' not in self.request.form:
            return None

    def getTermino(self):
        """devuelve la rama por la que se buscó"""
        try:
            catalogo=self.context.reference_catalog.lookupObject(self.request.form["rama"])
            return catalogo.Title
        except :
            print "CategoriaLista: bpContents.browser: no existe el UID"
            return None

    def relatedContent(self):
        catalog = getToolByName(self.context, 'portal_catalog')
        utils=Utilidades()


        idRama=self.request.form["rama"]

        seccionActual=utils.dameRutaSeccion(self.context)

        result=catalog({
            'articuloCategoria':idRama,
            'path':{'query': seccionActual, 'depth': 2},
            'sort_on': 'modified',
            'sort_order': 'reverse',
        })

        ls=[]
        for elem in result:
            elemObj=self.context.unrestrictedTraverse(elem.getPath())
            obj=dict()

            obj["titulo"]=elem.Title
            obj["descri"]=elem.Description
            obj["url"]=elem.getURL()
            obj["tipo"]="docFinal"
            obj["objeto"]=elem.portal_type
            if elem.portal_type in ("Products.bpContents.articulo","Products.bpContents.evento","Products.bpContent.galeria",):
                imgs=self.getImages(elemObj)
                if imgs:
                    obj["imagen"]=imgs[0]
                else:
                    obj["imagen"]=None
            else:
                obj["imagen"]=None

            ls.append(obj)
        if len(ls)>0:
            return ls
        else:
            return None

    def getImages(self,obj):
        """Toda las imagenes
        """
        from Products.bpContents.getImgTira import GetTiraImgs
        context = GetTiraImgs(obj)
        results = context.getTira()
        if results:
            return results
        else:
            return None

    def estaRegistradoElNav(self):
        request = self.context.REQUEST
        context = self.context
        view=self
        manager_name = 'plone.abovecontent'
        manager = queryMultiAdapter((context, request, view), IViewletManager, manager_name, default=None)
        manager.update()

        my_viewlet = [v for v in manager.viewlets if v.__name__ == 'interesesNav']

        if len(my_viewlet)>0:
            return True
        else:
            return False

    def registrarInteresesNav(self):
        context = aq_inner(self.context)
        request = self.request

        # Perform viewlet regisration look-up
        # from adapters registry
        reg = self.getViewletByName("interesesNav")
        if reg == None:
            return None

        # factory method is responsible for creating the viewlet instance
        factory = reg.factory
        try:
            viewlet = factory(context, request, self, None).__of__(context)
        except TypeError:
            # Bad constructor call parameters
            raise RuntimeError("Unable to initialize viewlet %s. Factory method %s call failed." % (name, str(factory)))

        return viewlet






    def getViewletByName(self, name):
        """ Viewlets allow through-the-web customizations.

        Through-the-web customization magic is managed by five.customerize.
        We need to think of this when looking up viewlets.

        @return: Viewlet registration object
        """
        views = customerize.registration.getViews(IBrowserRequest)

        for v in views:

            if v.provided == IViewlet:
                # Note that we might have conflicting BrowserView with the same name,
                # thus we need to check for provided
                if v.name == name:
                    return v

        return None

class EventsAjax(grok.View):
    """Una pagina que devuelve los eventos de un mes"""
    grok.context(Interface)
    grok.require('zope2.View')
    grok.name('monthajax')
    nomMeses=("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    month=0
    year=0
    mesActual=""

    def update(self):
        # Hide the editable-object border
        self.request.set('disable_border', True)
        #if 'rama' not in self.request.form:
        #    return None



    def getMonthEvents(self,mes):
        """Devuelve el mes anterior"""

        ##self.month = int(self.request.form["mes"])
        ##self.year= int(self.request.form["agno"])
        ##self.mesActual=self.nomMeses[self.month-1]

        self.month = mes
        lastDay=calendar.monthrange(self.year,self.month)
        end = DateTime(self.year,self.month,lastDay[1])
        start = DateTime(self.year, self.month,1)
        date_range_query = { 'query':(start,end), 'range': 'min:max'}
        items = self.context.portal_catalog.queryCatalog({
            "Language": "all", # Bypass LinguaPlone language check
            "portal_type":["Products.bpContents.evento"],
            "end" : date_range_query,
            "sort_on" : "start" })

        return items

    def dameWeekDay(self,DateTimeObj):

        nuevoF=date(DateTimeObj.year(),DateTimeObj.month(),DateTimeObj.day())
        return nuevoF.strftime("%A")

from zope.container.interfaces import IOrderedContainer
from persistent.list import PersistentList


class RedirectionView(grok.View):
    grok.context(IATFolder)
    grok.require('zope2.View')
    grok.name('redirect_view')


    def destacado(self):
        ### renderiza el ultimo elemento creado###
        ruta=""
        folder_contents =  self.context.getFolderContents()

        if len(folder_contents)>0:
            ruta=folder_contents[0].getPath()
        else:
            return None

        target_obj = self.context.restrictedTraverse(ruta)
        # Strip the target_obj of context with aq_base.
        # Put the target in the context of self.context.
        # getDefaultLayout returns the name of the default
        # view method from the factory type information


        default_page = target_obj


        return default_page



    def getImages(self):
        """Toda las imagenes
        """
        from Products.bpContents.getImgTira import GetTiraImgs
        dummyTira = GetTiraImgs(self.context)
        results = dummyTira.getTira()

        if results:
            return results
        else:
            return None

    def getCreatorInfo(self):
        """Devuelve los datos del responsable del artículo"""
        from Products.bpContents.CreatorInfo import CreatorInfo
        dataMember=CreatorInfo(self.context)
        return dataMember.getCreatorInfo()


class listadoEventos(grok.View):
    grok.context(Interface)
    grok.require('zope2.View')
    grok.name('listadoEventos')
    nomMeses=("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    month=0
    year=0
    mesActual=""
    vista="calendario"
    def update(self):
        # Hide the editable-object border

        if 'mes' in self.request.form:
            if self.request.form['mes']!='previos':
                self.vista="vistaMes"
            else:
                self.vista="vistaPrevios"

    def makeView(self):
        """Determina cual tipo de vista mostrar y busca resultados"""
        if self.vista=="calendario":
            return self.creaCalendario()

        if self.vista=="vistaMes":
            return self.creaCalendario()
            ##return self.creaCalendarioMes(int(self.request.form['mes']))

        if self.vista=="vistaPrevios":
            return self.creaCalendarioPrevios()

    def creaCalendario(self):
        """crea un diccionario con los mesese que restan hasta
        fin de año, incluye el mes actual"""
        now = datetime.datetime.now()
        mesActual=now.month
        meses=[]
        for indice in range(mesActual,len(self.nomMeses)+1):
            paqueteMes=self.creaUnMes(indice)
            if paqueteMes["cantEventos"]>0:
                meses.append(paqueteMes)

        return meses


    def creaCalendarioMes(self,mes):
        """Devuelve dicccionario con el calendario del mes en curso completo"""
        meses=[]
        paqueteMes=self.creaUnMes(mes)
        if paqueteMes["cantEventos"]>0:
            meses.append(paqueteMes)
        return meses

    def creaUnMes(self, numMes):
        """Metodo auxiliar para generar un objeto con el mes"""
        objMes=dict()
        objMes["nombre"]        =self.nomMeses[numMes-1]
        objMes["listaEventos"]  =self.dameEventosMes(numMes)
        objMes["cantEventos"]   =len(objMes["listaEventos"])
        return objMes

    def creaCalendarioPrevios(self):
        """Devuleve un diccionario con el calendario de los eventos concluidos hasta el mes actual"""
        now = datetime.datetime.now()
        mesActual=now.month
        meses=[]

        for indice in range(1,mesActual):
            paqueteMes=self.creaUnMes(indice)
            if paqueteMes["cantEventos"]>0:
                meses.append(paqueteMes)

        return meses


    def dameEventosFinalizados(self,mes):
        """Devuelve eventos con
        fecha de fin en el rango del mes"""

    def dameNombreDelMes(self,mes):
        """devuelve el nombre de un mes sguún la tupla"""
        return self.nomMeses[int(mes)]

    def dameNumeroDeNombre(self,nombre):
        """devuelve el nombre de un mes, dado un número"""
        return self.nomMeses.index(nombre)+1

    def dameEventosMes(self,mes):
        """devuelve un Diccionario con el
         mes:nombre mes
         cantEventos:cantidad de eventos
         listadoEventos: una tupla de un diccionario con
            titulo:
            url:
            descri:
            img

        """
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')


        #start =  DateTime() - (DateTime().day() -1)
        #end = start + calendar.monthrange(DateTime().year(),DateTime().month())[1]


        agno=DateTime().year()
        diaFinMes=calendar.monthrange(agno,mes)[1]
        start=DateTime(agno,mes,1)
        end =DateTime(agno,mes,diaFinMes)
        date_range_query = {'query': (start, end), 'range': 'min:max'}
        result=catalog(portal_type='Products.bpContents.evento',start=date_range_query,sort_on='start')

        if len(result)>0:
            return result
        else:
            return []

from Products.ATContentTypes.interfaces.document import IATDocument
class NoticiaView(grok.View):
    grok.context(IATDocument)
    grok.require('zope2.View')
    grok.name('noticiaview')

    def update(self):
        import pdb
        pdb.set_trace()
        pass

class IRegFormulario(Interface):
    """Marca para el custzacion"""

class ICaptchaSchema(Interface):
    """Subclass the standar gegistration
    """
    captcha = Captcha(
        title=u'Imagen de seguridad',
        description=(u'Tipee el codigo de la imagen.'),
    )

class RegFormulario(RegistrationForm):
    implements(IRegFormulario)

    @property
    def form_fields(self):
        # Get the fields so we can fiddle with them
        myfields = super(RegistrationForm, self).form_fields

        # Add a captcha field to the schema
        myfields += form.Fields(ICaptchaSchema)
        myfields['captcha'].custom_widget = CaptchaWidget

        # Perform any field shuffling here...
        # Return the fiddled fields...
        return myfields

